package com.zb.springboot_zb_sql.config;

import com.zb.springboot_zb_sql.bean.Role;
import com.zb.springboot_zb_sql.bean.Users;
import com.zb.springboot_zb_sql.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users =usersMapper.getUsers(username);
        if (users == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> authorities=new ArrayList<>();
        for (Role role : usersMapper.getUsers(username).getRoles()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }

        User userDetail=new User(username,passwordEncoder.encode(usersMapper.getUsers(username).getUserPassword()),authorities);
        return  userDetail;
    }
}
